package chapter03;

public class BuildTree106 {
    /**
     * 中序in[9,3,15,20,7] 后序pos[9,15,7,20,3]
     * 根据后序最后一个值start和start在中序位置划分左子树和右子树，中序左边值是左子树，中序右边值是右子树，递归左右子树
     * 中序in[9,3,15,20,7] 后序pos[9,15,7,20,3]
     *         -                            -
     *  process(inorder,inStart,inEnd,postorder,posStart,posEnd)
     *  利用中序inorder[inStart,inEnd]和后序postorder[posStart,posEnd]和构建树
     *  递归出口
     *      1).inStart>inEnd
     *          return null
     *      2).生成子树
     *        cur=postorder[posEnd]
     *        curNode=new TreeNode(cur) 生成当前节点
     *        index=0
     *         for i->(inStart,inEnd){
     *             if(inorder[i]==cur)
     *                 index=i  当前节点在中序数组中的下标
     *                 break
     *         curNode.left=process(inorder,inStart,index-1,postorder,posStart,posStart+index-inStart-1) 递归左子树
     *         curNode.right=process(inorder,index+1,inEnd,postorder,posStart+index-inStart,posEnd-1) 递归右子树
     *         return curNode 返回头节点
     */
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
   }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length==0){
            return null;
        }
        return process(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }

    public TreeNode process(int[] inorder,int inStart,int inEnd,int[] postorder,int posStart,int posEnd){
        if(inStart>inEnd){
            return null;
        }
        int cur=postorder[posEnd];
        TreeNode curNode=new TreeNode(cur);
        int index=0;
        for(int i=inStart;i<=inEnd;i++){
            if(cur==inorder[i]){
                index=i;
                break;
            }
        }
        curNode.left=process(inorder,inStart,index-1,postorder,posStart,posStart+index-inStart-1);
        curNode.right=process(inorder,index+1,inEnd,postorder,posStart+index-inStart,posEnd-1);
        return curNode;
    }
}
